import {default as request, AxiosInstance} from 'axios'
import * as cheerio from 'cheerio';

interface Cookie {
    name: string
    value: string
    expires: string
    max_age: number
    path: string
}

class Afunv {
    private cookie: Array<Cookie> = []
    private requestInstance: AxiosInstance
    private _token: string = ''
    constructor() {
        const instance: AxiosInstance = request.create({
            baseURL: 'https://have.afunv.xyz',
            maxRedirects: 0
        });
        const self = this;
        instance.interceptors.request.use(function (config) {
            // Do something before request is sent
            config.headers.cookie = self.getCookie()
            return config;
        }, function (error) {
            // Do something with request error
            return Promise.reject(error);
        });
        instance.interceptors.response.use(function (response) {
            // Do something before request is sent
            if(response.headers['set-cookie']){
                self.updateCookie(response.headers['set-cookie'])
            }
            // console.log(response)
            return response;
        }, function (error) {
            if(error.response.status === 302){
                if(error.response.headers['set-cookie']){
                    self.updateCookie(error.response.headers['set-cookie'])
                }
                return error.response;
            }
            // Do something with request error
            return Promise.reject(error);
        });
        instance.defaults.headers.common['user-agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36';

        this.requestInstance = instance;
    }
    private updateCookie (setCookie: Array<string>) {
        const rule = /([0-9a-zA-Z\-_]+)\=([0-9a-zA-Z%]+);\sexpires=([0-9a-zA-Z,\s\-:]+);\sMax-Age=(\d+);\spath=([a-z0-9A-Z\/]+)/
        for(let cookie of setCookie){
            if(!rule.test(cookie)) continue;
            const dataArray = cookie.match(rule)
            const name = dataArray[1]
            const value = dataArray[2]
            const expires = dataArray[3]
            const max_age = Number(dataArray[4])
            const path = dataArray[5]
            const cookieItem = this.cookie.find(e => e.name === name)
            if(!cookieItem){
                this.cookie.push({
                    name, value, expires, max_age, path
                })
            } else {
                cookieItem.value = value
                cookieItem.expires = expires
                cookieItem.max_age = max_age
                cookieItem.path = path
            }
        }
    }
    private getCookie =  ():string => {
        let cookies:Array<string> = []
        for(let item of this.cookie){
            cookies.push(`${item.name}=${item.value}`)
        }
        return cookies.join('; ')
    }
    private getLoginPage = async ():Promise<string> => {
        const pageReq = await this.requestInstance.get('/login')
        const {data} = pageReq
        const $ = cheerio.load(<string>data);
        const tokenInput = $('input[name="_token"]')
        if(!tokenInput['0']) throw new Error('获取不到Token输入框')
        console.log(tokenInput.attr('value'))
        return tokenInput.attr('value')
    }
    public login = async ():Promise<void> => {
        const _token = await this.getLoginPage()
        this._token = _token
        console.log(`登录账户: ${process.env.aFunVEmail}`)
        await this.requestInstance.post('/login', {
            email: process.env.aFunVEmail,
            password: process.env.aFunVPassword,
            _token
        })
    }
    public checkIn = async ():Promise<void> => {
        const checkReq = await this.requestInstance.post('/checkIn', {
            _token: this._token
        })
        const data = <any>checkReq.data
        if(data.status === 'fail') {
            throw new Error(data.message)
        }
        console.log('签到成功', data)
    }
}

export {Afunv}